using System.Collections.ObjectModel;
using System.Linq;
using Dino;
using NUnit.Framework;

namespace Tests.Dino.EntityFramework
{
    [TestFixture]
    public class SpecificContextTests
    {
        private SpecificContext _context;

        [SetUp]
        public void SetUp()
        {
            _context = new SpecificContext();
            _context.Database.CreateIfNotExists();
        }

        [TearDown]
        public void TearDown()
        {
            _context.Database.Delete();
        }

        [Test]
        public void Context_Name_Is_Actually_Used()
        {
            _context = new SpecificContext();
            _context.Database.CreateIfNotExists();
            // This is explicit in the config, verify that it's used.
            Assert.AreEqual(_context.Database.Connection.Database, "MyDb");
            _context.Database.Delete();
        }

        [Test]
        public void Can_add_entity_to_named_context()
        {
            var context = new SpecificContext();
            var unitOfWork = UnitOfWork.Configure()
                                        .Initialize();
            var unitOfWork1 = UnitOfWork.Configure(c => c.WithContext<SpecificContext>(context))
                                        .Initialize();

            var results = unitOfWork1.GetContext<SpecificContext>().Query<Entity>();

            Assert.AreEqual(0, results.Count());
        }

        [Test]
        public void Propertys_Can_Be_Injected_Uses_Named_Context_Naming()
        {
            _context = new SpecificContext();
            _context.Database.CreateIfNotExists();

            var unitOfWork1 = UnitOfWork.Configure(c => c.WithContext<TestContext>(_context)).Initialize();

            var foo = 5;
            var entityToAdd = new SomeEntity { SomeCollection = new ObservableCollection<Entity> { new Entity { Foo = foo }, new Entity { Foo = foo + 1 } } };

            var context = unitOfWork1.GetContext<TestContext>();
            context.Add(entityToAdd);
            unitOfWork1.Commit();

            var entityToInject = new Entity { Foo = foo };
            _context = new SpecificContext(t => t == typeof(Entity), t => entityToInject);

            unitOfWork1 = UnitOfWork.Configure(c => c.WithContext<TestContext>(_context)).Initialize();

            var result = unitOfWork1.GetContext<TestContext>().Query<SomeEntity>();

            Assert.AreEqual(1, result.Count());
            Assert.AreSame(entityToInject, result.First().Entity);
            Assert.AreEqual(_context.Database.Connection.Database, "MyDb");
        }
    }
}